﻿<template>
	<view>
		<scroll-view class="scroll" scroll-y="true">
			<view class="title">请认真填写以下信息</view>
			<u-form :model="form" ref="uForm" label-width="140">
				<view class="box">
					<view class="box-title">司机人员信息</view>
					<u-form-item label="姓名" prop="visitor" required>
						<u-input v-model="form.visitor" placeholder="请输入你的真实姓名" />
					</u-form-item>
					<u-form-item label="手机" prop="vphone" required>
						<u-input v-model="form.vphone" placeholder="请输入你的手机号码" />
					</u-form-item>
					<u-form-item label="性别" prop="sex" required>
						<u-radio-group v-model="form.sex">
							<u-radio v-for="(item, index) in sexList" :key="index" :name="item.value">
								{{ item.label }}
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="证件号" prop="idCard" required>
						<u-input v-model="form.idCard" placeholder="身份证号/台胞证/护照" />
					</u-form-item>
					<u-form-item label="身份证照片" prop="idCardImg" label-width="150" required>
						<u-upload ref="idCardImgUpload" name="file" :action="baseUrl+'/visitlog/UploadIdCardImg'" :file-list="idCardImgList" max-count="1" :show-progress="false" image-mode="widthFix" @on-success="idCardImgOnSuccess" @on-remove="idCardImgOnRemove"></u-upload>
					</u-form-item>
					<u-form-item label="来访单位" prop="vcompany" required>
						<u-input v-model="form.vcompany" placeholder="请输入你的来访单位" />
					</u-form-item>
					<u-form-item label="来访人数" prop="vnum" required>
						<u-input v-model="form.vnum" placeholder="一起人数,一人填单即可,后续分享给同伴" type="number" />
					</u-form-item>
					<u-form-item label="进入区域" prop="dept" required>
						<u-input v-model="form.dept" disabled placeholder="例如金茂一厂原料仓..." />
						<div @click="showDept = true" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; cursor: pointer;"></div>
						<u-icon slot="right" name="arrow-right" @click="showDept = true"></u-icon>
					</u-form-item>
					<u-form-item v-if="form.dept" label="进厂时间" prop="visitTime" required>
						<u-input v-model="form.visitTime" disabled placeholder="请选择进厂时间" />
						<div @click="showDate = true" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; cursor: pointer;"></div>
						<u-icon slot="right" name="arrow-right" @click="showDate = true"></u-icon>
					</u-form-item>
					<u-form-item v-if="form.dept" label="出厂时间" prop="vendTime" required>
						<u-input v-model="form.vendTime" disabled placeholder="出厂时间" />
						<!-- <div @click="showVend = true" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; cursor: pointer;"></div>
						<u-icon slot="right" name="arrow-right" @click="showVend = true"></u-icon> -->
					</u-form-item>
					<!-- <u-form-item :style="{color:isCheck?'#999':''}" label="进入区域" prop="visitSite" required>
						<u-input v-model="form.visitSite" disabled placeholder="请选择进入区域"/>
						<div @click="isCheck ? '' : showSite = true" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; cursor: pointer;"></div>
						<u-icon slot="right" name="arrow-right" @click="isCheck ? '' : showSite = true"></u-icon>
					</u-form-item> -->
					<u-form-item label="入厂事由" prop="vreason" required>
						<u-input border v-model="form.vreason" placeholder="如提货/送货/送施工材料等" type="textarea" />
					</u-form-item>
					<u-form-item label="人脸自拍" prop="vimg" label-width="150">
						<u-upload ref="vimgUpload" name="file" :action="baseUrl+'/visitlog/uploadvimg'" :file-list="vimgList" max-count="1" :show-progress="false" image-mode="widthFix" @on-success="onSuccess" @on-remove="onRemove"></u-upload>
					</u-form-item>
					<u-form-item label="车牌号" prop="carNo">
						<u-input v-model="form.carNo" placeholder="请输入你的车牌号" />
					</u-form-item>
					<u-form-item label="证件照(行驶证/驾驶证)和自带货照片(如有请上传)" label-position="top" prop="docImg" label-width="150" required>
						<u-upload ref="docImgUpload" :action="baseUrl+'/visitlog/uploaddocimg'" :file-list="docImgList" max-count="9" :show-progress="false" image-mode="widthFix"></u-upload>
					</u-form-item>
					<u-form-item label="自带货备注" prop="hwImg">
						<u-input border v-model="form.hwImg" placeholder="如有自带货请填写" type="textarea" />
					</u-form-item>
				</view>
				<view class="box">
					<view class="box-title">仓管人员信息相关</view>
					<!-- <u-form-item label="审批人" prop="leader" required>
						<u-input v-model="form.leader" disabled placeholder="请选择审批人的姓名" />
						<div @click="showLeader = true" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; cursor: pointer;"></div>
						<u-icon slot="right" name="arrow-right" @click="showLeader = true"></u-icon>
					</u-form-item> -->
					<u-form-item label="仓管人员" prop="staff">
						<u-input v-model="form.staff" placeholder="请输入仓管人员的姓名" />
					</u-form-item>
					<u-form-item label="手机">
						<u-input v-model="form.iphone" type="number" placeholder="请输入仓管人员的手机号码" />
					</u-form-item>
				</view>
			</u-form>
		</scroll-view>
		<u-row gutter="32" class="foot">
			<u-col span="6">
				<u-button type="error" @click="cancel">结束来访</u-button>
			</u-col>
			<u-col span="6">
				<u-button v-if="canFill" type="primary" :disabled="form.status==0?true:false" throttle-time="3000" @click="submit">提交</u-button>
			</u-col>
		</u-row>
		<view style="height: 51rpx;"></view>
		<u-picker v-model="showDate" mode="time" title="选择进厂时间" :params="params" @confirm="dateConfirm"></u-picker>
		<u-picker v-model="showVend" mode="time" title="选择出厂时间" :params="params" @confirm="vendConfirm"></u-picker>
		<u-select v-model="showSite" mode="mutil-column-auto" title="选择进入区域" :list="siteList" @confirm="siteConfirm"></u-select>
		<u-select v-model="showLeader" title="选择人员" :list="leaderList" @confirm="leaderConfirm"></u-select>
		<!-- <u-select v-model="showDept" title="选择部门" :list="deptList" @confirm="deptConfirm"></u-select> -->
		<multiple-picker 
			title="请选择部门" 
			:show="showDept" 
			:columns="deptList"
			:defaultIndex="deptIds"
			@confirm="deptConfirm" 
			@cancel="showDept = false"
		></multiple-picker>
		<u-modal v-model="showMsg" :title="title" :content="content" @confirm="confirmMsg"></u-modal>
		<u-modal v-model="show" @confirm="confirm" show-cancel-button content="确定吗？结束来访后能重新申请"></u-modal>
		<view v-if="form.status==0" class="top-msg green">已提交，信息审核中</view>
		<view v-if="form.status==20" class="top-msg red">申请已被拒绝，若有疑意请和受访人联系</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				canFill: true,
				newAddr: '未知',
				locationRef: null, // 用于接收定位对象
				show: false,
				baseUrl: '',
				deptIds: [],
				deptList: [],
				leaderAll: [],
				leaderList: [],
				docImgList: [],
				idCardImgList: [], // 身份证照片列表
				vimgList: [],  // 头像列表
				showDate: false,
				showVend: false,
				showSite: false,
				showLeader: false,
				showDept: false,
				showMsg:false,
				content:'',
				title:'',
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true
				},
				form: {
					visitor: '',
					vphone: '',
					sex: '',
					idCard: '',
					idCardImg: '',
					vcompany: '',
					vnum: null,
					visitTime: '',
					vendTime: '',
					vreason: '',
					visitSite: '',
					visitArea: '',
					vimg: '',
					carNo: '',
					docImg: [],
					hwImg: '',
					leader: '',
					dept: '',
					staff: '',
					iphone: '',
					status: -1, // 如 -1初次使用，0审核中，1已同意，2被拒绝
					position: '未知'
				},
				sexList: [
					{
						value: '1',
						label: '男'
					},
					{
						value: '2',
						label: '女'
					}
				],
				siteList: [
					{
						value: '1',
						label: '金茂一厂原料仓'
					},
					{
						value: '2',
						label: '金茂二厂原料仓'
					}
				],
				rules: {
					visitor: [
						{ 
							required: true, 
							message: '请输入', 
							// 可以单个或者同时写两个触发验证方式 
							trigger: ['change','blur'],
						}
					],
					vphone: [
						{
							required: true, 
							message: '请输入',
							trigger: ['change','blur'],
						},
						{
							// 自定义验证函数
							validator: (rule, value, callback) => {
								// 返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change','blur'],
						}
					],
					sex: [
						{ 
							required: true, 
							message: '请选择', 
							trigger: ['change','blur'],
							type: 'any'
						}
					],
					idCard: [
						{
							required: true, 
							message: '请输入',
							trigger: ['change','blur'],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.idCard(value) || this.$u.test.isTWCard(value) || this.$u.test.isHu(value);
							},
							message: '证件号不正确，如带X请大写',
							trigger: ['change','blur'],
						}
					],
					idCardImg: [
						{ 
							required: true, 
							message: '请输入', 
							trigger: ['change','blur'],
						}
					],
					vcompany: [
						{ 
							required: true, 
							message: '请输入', 
							trigger: ['change','blur'],
						}
					],
					vnum: [
						{ 
							required: true, 
							message: '请输入', 
							trigger: ['change','blur'],
							type: 'number'
						}
					],
					visitTime: [
						{ 
							required: true, 
							message: '请选择', 
							trigger: ['change','blur'],
						}
					],
					vendTime: [
						{ 
							required: true, 
							message: '请选择', 
							trigger: ['change','blur'],
						}
					],
					visitSite: [
						{ 
							required: true, 
							message: '请选择', 
							trigger: ['change','blur'],
						}
					],
					vreason: [
						{ 
							required: true, 
							message: '请输入', 
							trigger: ['change','blur'],
						}
					],
					dept: [
						{ 
							required: true, 
							message: '请选择', 
							trigger: ['change','blur'],
						}
					],
					leader: [
						{ 
							required: true, 
							message: '请选择', 
							trigger: ['change','blur'],
						}
					],
					// staff: [
					// 	{ 
					// 		required: true, 
					// 		message: '请输入', 
					// 		trigger: ['change','blur'],
					// 	}
					// ],
					// carNo: [
					// 	// { 
					// 	// 	required: true, 
					// 	// 	message: '请输入', 
					// 	// 	trigger: ['change','blur'],
					// 	// },
					// 	{
					// 		validator: (rule, value, callback) => {
					// 			if(value){
					// 				return this.$u.test.carNo(value) || this.$u.test.carNo2(value);
					// 			}else{
					// 				return true
					// 			}
					// 		},
					// 		message: '车牌号不正确',
					// 		trigger: ['change','blur'],
					// 	}
					// ]
				}
			}
		},
		mounted() {
			this.getOne()
		},
		onLoad() {
			this.baseUrl = this.$u.http.config.baseUrl
			this.getDepts()
			this.getSysUsers()
			
			this.getOne()
		},
		methods: {
			confirm() {
				const docImgArr = this.$refs.docImgUpload.lists
				.filter(item => item.progress === 100)
				.map(item => {
					if (item.response && item.response.result) {
						return {
							name: item.response.result.name, 
							url: item.response.result.url
						};
					} else {
						const urlParts = item.url.split('/');
						const name = urlParts[urlParts.length - 1];
						return { name, url: item.url };
					}
				});
				this.form.docImg = JSON.stringify(docImgArr)
				this.$u.post('/visitLogExtend/update',{...this.form,status:50}).then(res => {
					if(res.code==200){
						this.$u.toast('结束来访成功')
						uni.redirectTo({
							url: '/pages/index/index'
						})
					}else{
						this.$u.toast('删除失败',res.message)
					}	
				}).catch(err => {
					this.$u.toast('删除异常', err)
				})
			},
			cancel() {
				const oldVphone = uni.getStorageSync('vphone_2_key')
				if(oldVphone){
					this.show = true
				}else {
					return this.$u.toast('没有来访记录')
				}
			},
			getDepts() {
				this.$u.post('/visitLogExtend/SysOrgDeptIdDropdown').then(res => {
					if(res.code==200){
						const foundItem = res.result.find(item => item.code.indexOf('HZWGB') !== -1);
						if (foundItem) {
							const relatedItems = res.result.filter(item => item.pid === foundItem.value);
							this.deptList = relatedItems;
						}
					}else{
						this.$u.toast('获取部门失败',res.message)
					}
				}).catch(err => {
					this.$u.toast('获取部门异常',err)
				})
			},
			getSysUsers() {
				this.$u.post('/visitLogExtend/SysUserLeaderIdDropdown').then(res => {
					if(res.code==200){
						this.leaderList = []
						this.leaderAll = res.result
					}else{
						this.$u.toast('获取被访人失败',res.message)
					}
				}).catch(err => {
					this.$u.toast('获取被访人异常',err)
				})
			},
			idCardImgOnRemove() {
				this.$refs.idCardImgUpload.clear()
				this.form.idCardImg = ''
			},
			idCardImgOnSuccess(event) {
				if(event.code==200) {
					this.form.idCardImg = event.result.url
				}
			},
			onRemove() {
				this.$refs.vimgUpload.clear()
				this.form.vimg = ''
			},
			onSuccess(event) {
				if(event.code==200) {
					this.form.vimg = event.result.url
				}
			},
			getOne() {
				this.idCardImgList = []
				this.vimgList = []
				const oldVphone = uni.getStorageSync('vphone_2_key')
				if(oldVphone){
					this.$u.get('/visitlog/getvisit',{
						type:2,
						vphone:oldVphone
					},{
						'Content-Type': 'application/json;charset=UTF-8',
						'Content-Type': 'application/x-www-form-urlencoded'
					}).then(res => {
						if(res.code==200){
							const obj = res.result
							this.form = {
								id: obj.id,
								type: obj.type,
								visitor: obj.visitor,
								vphone: obj.vphone,
								sex: obj.sex,
								idCard: obj.idCard,
								idCardImg: obj.idCardImg,
								vcompany: obj.vcompany,
								vnum: obj.vnum,
								visitTime: obj.status==50?'':obj.visitTime,
								vendTime: obj.status==50?'':obj.vendTime,
								visitSite: obj.status==50?'':obj.visitSite,
								visitArea: obj.status==50?'':obj.visitArea,
								vreason: obj.status==50?'':obj.vreason,
								vimg: obj.vimg,
								carNo: obj.carNo,
								docImg: JSON.parse(obj.docImg),
								hwImg: obj.status==50?'':obj.hwImg,
								leaderId: obj.status==50?'':obj.leaderId,
								leader: obj.status==50?'':obj.leaderIdRealName,
								deptId: obj.status==50?'':obj.deptId,
								dept: obj.status==50?'':obj.visitArea,
								staff: obj.status==50?'':obj.staff,
								iphone: obj.status==50?'':obj.iphone,
								status: obj.status
							}
							if(this.form.idCardImg) {
								this.idCardImgList.push({ url: this.form.idCardImg })
							}
							if(this.form.vimg) {
								this.vimgList.push({ url: this.form.vimg })
							}
							this.docImgList = JSON.parse(obj.docImg)
							
							if(obj.status==0) {
								const labels = obj.visitArea.split(',')
								this.deptIds = labels.map(label => {
									const item = this.deptList.find(item => item.label === label.trim())
									return item ? item.value+'' : null
								}).filter(value => value !== null)
							}
							
							// if(obj.status==0) {
							// 	this.updateAddr()
							// }
							if(obj.status==10 || obj.status==25 || obj.status==30 || obj.status==40 || obj.status==45){
								uni.redirectTo({
									url: '/pages/my/askCode?content='+obj.id+','+obj.status+','+obj.type
								})
							}
						}else{
							this.$u.toast(res.message)
						}
					}).catch(err => {
						this.$u.toast(err)
					})
				}
			},
			updateAddr() {
				const docImgArr = this.$refs.docImgUpload.lists
				.filter(item => item.progress === 100)
				.map(item => {
					if (item.response && item.response.result) {
						return {
							name: item.response.result.name, 
							url: item.response.result.url
						};
					} else {
						const urlParts = item.url.split('/');
						const name = urlParts[urlParts.length - 1];
						return { name, url: item.url };
					}
				});
				this.form.docImg = JSON.stringify(docImgArr)
				this.$u.post('/visitLogExtend/update',{...this.form,position:this.newAddr,isBeShared:-1}).then(res => {
					if(res.code!=200){
						this.$u.toast('位置更新失败',res.message)
					}
				}).catch(err => {
					this.$u.toast('位置更新异常', err)
				})
			},
			siteConfirm(e) {
				this.form.visitSite = e[0].label+' '+e[1].label
			},
			dateConfirm(e) {
				this.form.visitTime = e.year + '-' + e.month + '-' + e.day + ' ' + e.hour + ':' + e.minute;
				
				// 计算 vendTime 的小时
				let hour = parseInt(e.hour) + 6;
				let day = parseInt(e.day);
				let month = parseInt(e.month);
				let year = parseInt(e.year);
			
				// 针对特定部门的处理
				if (this.form.dept.includes('人資部餐厅貨管')) {
					day += 30; // 这里需要确认是否是想在天数上加30
				}
			
				// 如果小时数超过 24，则需要增加一天，并且调整小时数
				if (hour >= 24) {
					hour -= 24; // 重置小时数
					day++; // 增加一天
				}
			
				// 处理日期的溢出
				const monthDays = [
					31, // 一月
					(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28, // 二月
					31, // 三月
					30, // 四月
					31, // 五月
					30, // 六月
					31, // 七月
					31, // 八月
					30, // 九月
					31, // 十月
					30, // 十一月
					31  // 十二月
				];
			
				// 检查日期是否超出当前月份最大天数
				while (day > monthDays[month - 1]) {
					day -= monthDays[month - 1]; // 减去当前月份的天数
					month++; // 增加月份
					// 检查是否需要改变年份
					if (month > 12) {
						month = 1; // 重置为1月
						year++; // 增加年份
					}
				}
			
				this.form.vendTime = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(e.minute).padStart(2, '0')}`;
			},
			vendConfirm(e) {
				this.form.vendTime = e.year+'-'+e.month+'-'+e.day+' '+e.hour+':'+e.minute
			},
			deptConfirm(e) {
				var arr = e.value
				// this.form.deptId = arr[Math.floor(Math.random() * arr.length)]
				this.form.deptId = e.selected[0].value
				// this.form.dept = e.selected[0].label
				this.leaderList = this.leaderAll.filter(item => item.orgId == this.form.deptId)
				if(this.leaderList) {
					this.form.leaderId = this.leaderList[0].value
					this.form.leader = this.leaderList[0].label
				}else{
					this.$u.toast('注意没审批人',)
				}
				
				let temp = []
				e.selected.forEach(item => {
					temp.push(item.label)
				})
				this.form.dept = temp.toString()
				this.deptIds = e.value
				this.form.visitArea = this.form.dept
				this.showDept = false
			},
			leaderConfirm(e) {
				this.form.leaderId = e[0].value
				this.form.leader = e[0].label
			},
			confirmMsg() {
				this.showMsg = false
				if(this.title == '提交成功'){
					uni.redirectTo({
						url: '/pages/index/index'
					})
				}
			},
			submit() {
				const docImgArr = this.$refs.docImgUpload.lists
				.filter(item => item.progress === 100)
				.map(item => {
					if (item.response && item.response.result) {
						return {
							name: item.response.result.name, 
							url: item.response.result.url
						};
					} else {
						const urlParts = item.url.split('/');
						const name = urlParts[urlParts.length - 1];
						return { name, url: item.url };
					}
				});
				this.form.docImg = JSON.stringify(docImgArr)
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if(this.form.status==0 || this.form.status==20) {
							this.$u.post('/visitLogExtend/update',{...this.form,type:2,status:0}).then(res => {
								uni.setStorageSync('vphone_2_key', this.form.vphone)
								if(res.code==200){
									this.showMsg = true
									this.title = '提交成功'
									this.content = '请等待审核 稍后可再次到此页面查询结果'
								}else{
									this.showMsg = true
									this.title = '提交失败'
									this.content = res.message
								}
							}).catch(err => {
								this.showMsg = true
								this.title = '提交失败'
								this.content = err
							})
						}else{
							this.$u.post('/visitLogExtend/add',{...this.form,position:this.newAddr,type:2,status:0}).then(res => {
								uni.setStorageSync('vphone_2_key', this.form.vphone)
								if(res.code==200){
									this.showMsg = true
									this.title = '提交成功'
									this.content = '请等待审核 稍后可再次到此页面查询结果'
								}else{
									this.showMsg = true
									this.title = '提交失败'
									this.content = res.message
								}
							}).catch(err => {
								this.showMsg = true
								this.title = '提交失败'
								this.content = err
							})
						}
					}
				});
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>

<style scoped>
	.title {
		font-size: 40rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #000000;
		padding: 67rpx 0 10rpx 40rpx;
	}
	
	.box {
		width: 690rpx;
		background: #fff;
		margin: auto;
		margin-top: 30rpx;
		padding: 0 23rpx;
		border-radius: 12rpx;
	}
	
	.box-title {
		font-size: 32rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #000000;
		padding-top: 48rpx;
	}
	
	.btn {
		width: 690rpx;
		background: #1976D2;
		color: #fff;
		margin-top: 66rpx;
	}
	
	.top-msg {
		display: flex;
		justify-content: center;
		align-items: center;
		position: fixed;
		top: var(--window-top);
		width: 100%;
		height: 88rpx;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
		z-index: 999;
	}
	.top-msg.green {
		background: #19BE6B;
	}
	.top-msg.red {
		background: #FA3534;
	}
	
	.scroll {
		height: calc(100vh - var(--window-top) - var(--window-bottom) - 142rpx);
		width: 100%;
	}
	
	.foot {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 112rpx;
		border-top: 1rpx solid #F5F5F5;
		background: #fff;
	}
	
</style>
